package com.ruoyi.web.controller.translation;

import com.ruoyi.translat.mapper.TranslatSecretMapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/10/9
 */
public class TencentTranslator {

    private static final String SECRET_ID = "AKIDGOJ1VmHfqpfOvGQNpEYjhSzINFtJYfcL";
    private static final String SECRET_KEY = "bzA9QYVGn6D6lCQTLzPeiYAZlmaBbonZ";
    private static final String ENDPOINT = "tmt.tencentcloudapi.com";
    private static final String REGION = "ap-shanghai";

    private TmtClient client;

    private static final Logger log = LoggerFactory.getLogger(TencentTranslator.class);


    @Resource
    TranslatSecretMapper translatSecretMapper;

    public TencentTranslator() {
        // 初始化认证对象
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);

        // 客户端配置
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(ENDPOINT);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        this.client = new TmtClient(cred, REGION, clientProfile);
    }

    /**
     * 文本翻译
     *
     * @param sourceText 源文本
     * @param sourceLang 源语言，如：zh
     * @param targetLang 目标语言，如：en
     * @return 翻译结果
     */
    public String translate(String sourceText, String sourceLang, String targetLang) {
        try {
            TextTranslateRequest req = new TextTranslateRequest();
            req.setSourceText(sourceText);
            req.setSource(sourceLang);
            req.setTarget(targetLang);
            req.setProjectId(0L); // 项目ID，0表示默认项目

            TextTranslateResponse resp = client.TextTranslate(req);
            return resp.getTargetText();

        } catch (TencentCloudSDKException e) {
            System.err.println("翻译失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 自动检测语言并翻译
     *
     * @param sourceText 源文本
     * @param targetLang 目标语言
     * @return 翻译结果
     */
    public String autoTranslate(String sourceText, String targetLang) {
        return translate(sourceText, "auto", targetLang);
    }
}
